<?php
/**
 *
 * @author zhouming
 *
 */
class Order extends MY_Controller{
    
    protected function init(){
        if(!is_cli()){
            exit("请在命令行下执行！");
        }
    }
    
    public function index($a){
        $this->load->model('order_model');
        $this->order_model->handedOutCommission($a);
    }
    /**
     * 结算用户推荐提成
     * @param unknown $pid 启动进程编号
     */
    public function account_for_recommender($pid = 0,$totalPid = 10){
    	$key = Tool::getCacheKey('account_for_recommender' . $pid);
    	$this->load->driver('cache' , array('adapter' => 'redis'));
    	$pid_exist = $this->cache->redis->get($key);
    	if($pid_exist == 1){
    		echo "程序正在运行！";
    		exit();
    	}else{
//     		$this->cache->redis->save($key , 1 , 0);
    		$this->load->model('order_model');
    		$total = $this->order_model->getNotAccountForRecommenderOrderNum();
    		if($pid == 0){
    			$order_list = $this->order_model->getNotAccountForRecommenderOrderList();
    		}else{
    			$limit = ceil($total/$totalPid);
    			$start = ($pid - 1) * $limit;
    			$order_list = $this->order_model->getNotAccountForRecommenderOrderList($start,$limit);
    		}
    		foreach($order_list as $value){
    			$this->order_model->handedOutCommission($value['order_id']);
			}    		
    	}
    	
    	$this->cache->redis->delete($key);
    }
    /**
     * 结算区域经理配送提成
     * @param unknown $pid 启动进程编号
     */
    public function account_for_manager($pid = 0,$totalPid = 10){
        $key = Tool::getCacheKey('account_for_manager' . $pid);
        $this->load->driver('cache' , array('adapter' => 'redis'));
        $pid_exist = $this->cache->redis->get($key);
        if($pid_exist == 1){
            echo "程序正在运行！";
            exit();
        }else{
            $this->cache->redis->save($key , 1 , 0);
            $this->load->model('order_model');
            $total = $this->order_model->getNotAccountForManagerOrderNum();
            if($pid == 0){
                $order_list = $this->order_model->getNotAccountForManagerOrderList();
            }else{
                $limit = ceil($total/$totalPid);
                $start = ($pid - 1) * $limit;
                $order_list = $this->order_model->getNotAccountForManagerOrderList($start,$limit);
            }
            foreach($order_list as $value){
                $this->order_model->handedOutManagerCommission($value['order_id']);
            }
        }
         
        $this->cache->redis->delete($key);
    }
    /**
     * 退还取消订单的消费金额
     * @param number $pid
     * @param number $totalPid
     */
    public function return_cancelled_order_amount($pid = 0,$totalPid = 10){
    	$key = Tool::getCacheKey('return_canceled_order_ammount' . $pid);
    	$this->load->driver('cache' , array('adapter' => 'redis'));
    	$pid_exist = $this->cache->redis->get($key);
    	if($pid_exist == 1){
    		echo "程序正在运行！";
    		exit();
    	}else{
    		$this->cache->redis->save($key , 1 , 0);
    		$this->load->model('order_model');
    		$total = $this->order_model->getNotReturndAmmountOrderNum();
    		if($pid == 0){
    			$order_list = $this->order_model->getNotReturndAmmountOrderList();
    		}else{
    			$limit = ceil($total/$totalPid);
    			$start = ($pid - 1) * $limit;
    			$order_list = $this->order_model->getNotReturndAmmountOrderList($start,$limit);
    		}
    		foreach($order_list as $value){
    			$this->order_model->returnCancelledOrderAmmount($value['order_id']);
    		}
    	}
    	
    	$this->cache->redis->delete($key);
    	
    }
    
    /**
     * 处理在线支付订单的状态
     * @param number $pid
     * @param number $totalPid
     */
    public function handle_online_pay_order($pid = 0,$totalPid = 10){
        $key = Tool::getCacheKey('return_canceled_order_ammount' . $pid);
        $this->load->driver('cache' , array('adapter' => 'redis'));
        $pid_exist = $this->cache->redis->get($key);
        if($pid_exist == 1){
            echo "程序正在运行！";
            exit();
        }else{
            $this->cache->redis->save($key , 1 , 0);
            $this->load->model('order_model');
            $total = $this->order_model->getOrderOnlineNotPayNum();
            if($pid == 0){
                $order_list = $this->order_model->getOrderOnlineNotPay();
            }else{
                $limit = ceil($total/$totalPid);
                $start = ($pid - 1) * $limit;
                $order_list = $this->order_model->getOrderOnlineNotPay($start,$limit);
            }
            foreach($order_list as $value){
                if($value['needPay'] > 0){
                    if($value['send_time'] == null){
                        $this->load->model('user_model');
                        $userInfo = $this->user_model->getUserInfoForId($value['user_id']);
                        if($userInfo['wx_openid']){
                            $remark = '详情点这里!';
                            $this->config->load('wechat_config', TRUE);
                            $config = $this->config->item('wechat_config');
                            $config = $config['mobile'];
                            $this->load->model('wechat_model');
                            $this->wechat_model->init($config);
                            $result = $this->wechat_model->sendPayNotifyMessage($userInfo['wx_openid'], $value['order_num'], $value['order_time'], $value['total'], $value['needPay'], $remark);
                            if($result['errmsg'] == 'ok'){
                                $this->load->model('order_model');
                                $this->order_model->addOrderOnlineNotPayNotifyLog($value['id']);
                            }
                        } 
                    }else{
                        $current_time = time();
                        $send_time = strtotime($value['send_time']);
                        if($current_time - $send_time > 900){
                            $data = array('status'=>3);
                            $this->db->trans_start();
                            $this->order_model->updateOrder($value['id'], $data);
                            $this->order_model->addOrderCancelledRecord($value['id'], 0, 4,'在线订单未支付系统自动取消');
                            $this->db->trans_complete();
                        }
                    }
                }else{
                    $data = array('real_pay'=>$value['total'],'status'=>0);
                    $this->order_model->updateOrder($value['id'], $data);
                }
            }
        }
         
        $this->cache->redis->delete($key);
         
    }
    
    public function recoverCommission(){
        $order_list = $this->db->select('id,order_id')
    	->from('dwf_order_completed')->get()->result_array();
        $user_id = array();
        $this->load->model('user_model');
        $this->load->model('order_model');
    	foreach($order_list as $value){
    	    $commission_record = $this->db->where(array('order_num'=>$value['order_id'],'operate'=>'+'))->get('dwf_count_record')->result_array();
    	    foreach($commission_record as $val){
    	        $user_id[] = $val['user_id'];
    	        $this->db->where('id',$val['id'])->delete('dwf_count_record');
    	        $this->user_model->updateUserCountBalance($val['user_id'], '-', $val['amount']);
//     	        $this->user_model->addUserCountRecord($val['user_id'], $val['amount'], '-' , 0 , $val['order_num'] ,'追回订单提成');
    	    }
    	    $this->order_model->handedOutCommission($value['order_id']);
    	}
    	$user_id = array_unique($user_id);
    	$amount = 0;
    	foreach($user_id as $k=>$v){
    	    $user_info = $this->user_model->getUserInfoForId($v);
    	    if($user_info['count_balance'] < 0){
    	        $amount += -($user_info['count_balance']);
    	    }else{
    	        unset($user_id[$k]);
    	    }
    	}
    	print_r($user_id);
    	echo "\n";
    	echo count($user_id);
    	echo "\n";
    	echo $amount;
    	foreach($user_id as $vv){
    	    $this->db->set('count_balance',0.00)->where('id',$vv)->update('dwf_user_basic');
    	}
    }
}